package com.jp.knowledge.activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.FragMentAdapter;
import com.jp.knowledge.adapter.ProductInterfaceRightMenuAdapter;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.fragment.ProduceUIFragment;
import com.jp.knowledge.fragment.ProductFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.ProductUIMenuModel;
import com.jp.knowledge.model.ProductUIModel;
import com.jp.knowledge.model.ProductVersion;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/5/11.
 */

public class ProductInterfaceActivity extends SlidingActivity implements View.OnClickListener,  ResultSubscriber.OnResultListener  {

    private static final int GET_RIGHT_MENU_LIST_CODE = 0x01;
    @ViewInject(R.id.icon_right)
    private ImageView openRightBtn;
    @ViewInject(R.id.drawerLayout)
    private DrawerLayout drawerLayout;
    @ViewInject(R.id.right_menu)
    private LinearLayout rightMenuView;
    @ViewInject(R.id.right_rv)
    private RecyclerView rightMenuRv;

    @ViewInject(R.id.tab_view)
    private TabView tabView;

    @ViewInject(R.id.view_page)
    private ViewPager viewPager;

    private List<Fragment> fragments;
    private FragMentAdapter fragMentAdapter;

    private List<ProductUIMenuModel> menuModelList;
    private ProductInterfaceRightMenuAdapter rightMenuAdapter;

    private List<ProductUIModel> productUIModelList;
    //    private ProductUIAdapter productUIAdapter;
    private ArrayList<String> medias;
    private StaggeredGridLayoutManager gridLayoutManager;

    private String rightMenuCachePath;
    private FileCacheManager cacheManager;

    private int action;
    private boolean product;
    private ProductVersion  productVersion;
    @Override
    protected int getResourceId() {
        return R.layout.activity_product_interface;
    }

    @Override
    protected void init() {
        initTitleBar();
        action = getIntent() .getIntExtra("action",1);
        product = getIntent().getBooleanExtra("product",false);
        if(product){
            productVersion = (ProductVersion) getIntent().getSerializableExtra("product_data");
            if(productVersion!=null){
                topName.setText(productVersion.getName());
            }
        }
        gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        gridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        rightMenuRv.setHasFixedSize(true);
        rightMenuRv.setLayoutManager(new LinearLayoutManager(mContext));
        rightMenuRv.addItemDecoration(new JpDiver(mContext));

        menuModelList = new ArrayList<>();
        rightMenuAdapter = new ProductInterfaceRightMenuAdapter(mContext, menuModelList);
        rightMenuRv.setAdapter(rightMenuAdapter);
        rightMenuAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                if(position == rightMenuAdapter.getSelectedPosition())
                    return;
                rightMenuAdapter.setSelectedPosition(position);
                rightMenuAdapter.notifyDataSetChanged();
                drawerLayout.closeDrawer(rightMenuView);
//                refreshContent.scrollToPosition(0);
//                refreshLayout.autoRefresh();

                String tagId = menuModelList.get(rightMenuAdapter.getSelectedPosition()).getId();
                if(tagId == null)
                    topName.setText(getIntent().getStringExtra("name"));
                else
                    topName.setText(menuModelList.get(rightMenuAdapter.getSelectedPosition()).getName());
                ((ProduceUIFragment)fragments.get(0)).autoRefresh(tagId);
            }
        });
        medias = new ArrayList<>();
        productUIModelList = new ArrayList<>();
        rightMenuCachePath = mContext.getCacheDir() + "/productInterfaceRightMenu_" + action + ".dat";
        cacheManager = new FileCacheManager();

        initFragment();
        readRightMenuData();
    }

    public int getAction() {
        return action;
    }

    /***
     * 初始化fragment
     */
    private void initFragment() {
        fragments = new ArrayList<>();
        List<String> tabNames = new ArrayList<>();
        tabNames.add("界面");
        fragments.add(new ProduceUIFragment());
//        if(!product) {
//            fragments.add(new ProductFragment());
//            tabNames.add("产品");
//        }
        fragMentAdapter = new FragMentAdapter(getSupportFragmentManager(),fragments);
        viewPager.setAdapter(fragMentAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
            @Override
            public void onPageScrollStateChanged(int state) {}
            @Override
            public void onPageSelected(int position) {
                if(position == 0) {
                    openRightBtn.setVisibility(View.VISIBLE);
                    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                } else {
                    openRightBtn.setVisibility(View.GONE);
                    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                }
            }
        });
//        if(!product) {
//            tabView.setupWithViewPager(viewPager);
//            tabView.setTabItems(tabNames);
//        }else {
//            tabView.setVisibility(View.GONE);
//        }
        tabView.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if(drawerLayout.isDrawerOpen(rightMenuView))
            drawerLayout.closeDrawer(rightMenuView);
        else
            super.onBackPressed();
    }

    private void initTitleBar(){
        if(productVersion!=null){
            topName.setText(productVersion.getName());
        }else {
            topName.setText(getIntent().getStringExtra("name"));
        }
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.VISIBLE);
        openRightBtn.setVisibility(View.VISIBLE);
        openRightBtn.setImageResource(R.mipmap.leidacebianlan);
        leftIcon.setOnClickListener(this);
        rightIcon.setOnClickListener(this);
        openRightBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.icon_left:
                finish();
                break;
            case R.id.icon_serach:
                startActivity(new Intent(mContext, SearchSimpleActivity.class)
                        .putExtra("searchType", 15)
                        .putExtra("action", action));
                break;
            case R.id.icon_right:
                drawerLayout.openDrawer(rightMenuView);
                break;
        }
    }

    private void readRightMenuData(){
        Observable.create(new Observable.OnSubscribe<List<ProductUIMenuModel>>() {
            @Override
            public void call(Subscriber<? super List<ProductUIMenuModel>> subscriber) {
                List<ProductUIMenuModel> data = (List<ProductUIMenuModel>) cacheManager.readObject(rightMenuCachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ProductUIMenuModel>>() {
                    @Override
                    public void onCompleted() {
                        getRightMenuData();
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<ProductUIMenuModel> data) {
                        if(data != null) {
                            menuModelList = data;
                            rightMenuAdapter.updateAdapter(menuModelList);
                        }
                        onCompleted();
                    }
                });
    }


    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }



    private void getRightMenuData(){
        JsonObject param = new JsonObject();
        param.addProperty("action",action);
        HttpHelper.getInstance(mContext).catalogTree(param, GET_RIGHT_MENU_LIST_CODE, this);
    }



    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
    }
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext, data.getMessage());
            onError(requestType);
        } else if(requestType == GET_RIGHT_MENU_LIST_CODE){
            menuModelList = data.getList(ProductUIMenuModel.class);
            if(menuModelList == null)
                menuModelList = new ArrayList<>();
            ProductUIMenuModel model = new ProductUIMenuModel();
            model.setName("全部");
            menuModelList.add(0, model);
            rightMenuAdapter.updateAdapter(menuModelList);
            saveCache(menuModelList, rightMenuCachePath);
        }
    }
}
